<template>
  <div class="container">
    <index-head></index-head>
    <div class="main clearfix">
      <div class="breadcrumb_mainBody_tab_tilte custom_breadcrumb">
        <index-breadcrumb></index-breadcrumb>
        <div class="el-radio-padding custom_radio_select">
          <span class="el-radio-color">进出口类型：</span>
          <el-radio-group v-model="iETypeRadio" @input="termSubmit">
            <el-radio :label="1">进口</el-radio>
            <el-radio :label="0">出口</el-radio>
            <el-radio :label="10">进出口</el-radio>
          </el-radio-group>
          <span class="el-radio-padding-left">币种：</span>
          <el-radio-group v-model="currencyTypeRadio" @input="termSubmit">
            <el-radio :label="1">人民币</el-radio>
            <el-radio :label="2">美元</el-radio>
          </el-radio-group>
        </div>
        <div style="display: inline-block; position: relative; left: 120px;">
          <ul class="mainBody_tab_tilte clearfix">
            <li @click="output">
              <img src="../assets/image/mainCon_icon2.png" />
              <span>导出</span>
            </li>
            <li @click="print">
              <img src="../assets/image/mainCon_icon3.png" />
              <span>打印</span>
            </li>
            <li @click="downloadImpByChart">
              <img src="../assets/image/mainCon_icon4.png" />
              <span>保存</span>
            </li>
          </ul>
        </div>
      </div>
      <div class="mainPositionWin" v-show="mainPositionWinShow">
        <div class="positionTitle">
          <div class="clearfix">
            <p class="positionTitle_a">条件</p>
            <p class="positionTitle_close" @click="conditionsClose">
              <img src="../assets/image/close.png" />
            </p>
            <p class="positionTitle_clear" @click="conditionsClear">清空</p>
            <p class="positionTitle_extract" @click="termSubmit">数据提取</p>
          </div>
          <div class="navCntBox clearfix">
            <!--商品名称-->
            <div class="getIndexBox">
              <span class="titleYellow">商品</span>
              <el-checkbox-group v-model="getIndex" @change="handleCheckedGetIndexChange">
                <el-checkbox v-for="getIndexName in getIndexs" :label="getIndexName.key" :key="getIndexName.key">
                  {{ getIndexName.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!--贸易方式-->
            <div class="getIndexBox">
              <span class="titleYellow">贸易方式</span>
              <el-checkbox-group v-model="getTradeMode" @change="handleCheckedGetTradeModeChange">
                <el-checkbox v-for="getTradeMode in getTradeModes" :label="getTradeMode.key" :key="getTradeMode.key">
                  {{ getTradeMode.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!--国别-->
            <div class="getIndexBox">
              <span class="titleYellow">国别</span>
              <el-checkbox-group v-model="getTradePartner" @change="handleCheckedGetTradePartnerChange">
                <el-checkbox v-for="getTradePartner in getTradePartners" :label="getTradePartner.key" :key="getTradePartner.key">
                  {{ getTradePartner.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!--注册地-->
            <div class="getRegionBox">
              <span class="titleYellow">地区</span>
              <el-checkbox-group v-model="getRegion" @change="handleCheckedGetRegionChange">
                <el-checkbox v-for="item in getRegions" :label="item.key" :key="item.key">{{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!--时间-->
            <div class="getTimeBox">
              <p class="titleYellow">时间</p>
              <el-checkbox-group v-model="getTime" @change="handleCheckedGetTimeChange">
                <el-checkbox v-for="getTimeName in getTimes" :label="getTimeName.key" :key="getTimeName.key">
                  {{ getTimeName.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div class="mainTerm">
        <el-tabs v-model="activeName" type="card">
          <!--商品名称-->
          <el-tab-pane label="商品" name="first">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterText" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="data" :props="defaultProps" :filter-node-method="filterNode" ref="tree" show-checkbox node-key="code" @node-click="nodeClickHandle" :default-expanded-keys="[]" @check-change="checkChangeHandle"></el-tree>
            </div>
          </el-tab-pane>
          <!--贸易方式-->
          <el-tab-pane label="贸易方式" name="second">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextTradeMode" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextTradeModeClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataTradeMode" :props="defaultPropsTradeMode" :default-expand-all="true" :filter-node-method="filterNodeTradeMode" ref="treeTradeMode" show-checkbox node-key="code" @node-click="nodeClickHandleMode" :default-expanded-keys="[]" @check-change="checkChangeHandleMode"></el-tree>
            </div>
          </el-tab-pane>
          <!--贸易伙伴-->
          <el-tab-pane label="国别" name="three">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextTradePartner" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextTradePartnerClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataTradePartner" :props="defaultPropsTradePartner" :default-expand-all="true" :filter-node-method="filterNodeTradePartner" ref="treeTradePartner" show-checkbox node-key="code" @node-click="nodeClickHandlePartner" :default-expanded-keys="[]" @check-change="checkChangeHandlePartner">
              </el-tree>
            </div>
          </el-tab-pane>
          <!--地区-->
          <el-tab-pane label="地区" name="four">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextRegion" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextRegionClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataRegion" :props="defaultPropsRegion" :default-expand-all="true" :filter-node-method="filterNodeRegion" ref="treeRegion" show-checkbox node-key="code" @node-click="nodeClickHandleRegion" :default-expanded-keys="[]" @check-change="checkChangeHandleRegion">
              </el-tree>
            </div>
          </el-tab-pane>
          <!--时间-->
          <el-tab-pane label="时间" name="five">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextTime" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextTimeClear" />
            </div>

            <el-dropdown trigger="click" @command="timeFilterSelectFn" style="color: #fff" class="timeSelect">
              <span class="el-dropdown-link">
                {{ timeFilterSelectVal }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="item" v-for="item in timeFilterSelectArr" :key="item.label">{{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <div class="tree">
              <el-tree class="filter-tree" :data="dataTime" :props="defaultPropsTime" :default-expand-all="true" :filter-node-method="filterNodeTime" ref="treeTime" show-checkbox node-key="id" @node-click="nodeClickHandleTime" :default-expanded-keys="[]" @check-change="checkChangeHandleTime">
              </el-tree>
            </div>
          </el-tab-pane>
        </el-tabs>
        <p @click="termlook" class="conditions">查看条件</p>
      </div>
      <div class="mainContainer">

        <div style="display: flex; flex-wrap: nowrap; justify-content: space-between;align-items: center;">
          <!-- <el-tabs v-model="value" type="card" v-show="shoutabs.length !== 1" style="width:40%" @tab-click="legendClick">
            <el-tab-pane v-for="(item,index) in tablist" :key="index" :label="item.label" :name="item.value" v-if="!item.visible"></el-tab-pane>
          </el-tabs> -->
          <!-- <div class="mainBody" ref="imageWrapper">
            <a :href="downImg" :download="picName" id="downImg" style="display: none"></a>
            <ul class="mainBody_tab_tilte clearfix">
              <li @click="output">
                <img src="../assets/mainCon_icon2.png" />
                <span>导出</span>
              </li>
              <li @click="print">
                <img src="../assets/mainCon_icon3.png" />
                <span>打印</span>
              </li>
              <li @click="downloadImpByChart">
                <img src="../assets/mainCon_icon4.png" />
                <span>保存</span>
              </li>
            </ul>
          </div>   -->
        </div>
        <div class="mainBody" ref="imageWrapper">
          <div class="mainBody_tab_content">
            <div>
              <div v-show="anaDataShow">
                <h1 class="anaDataTitle" @click="anaDataTitleBtn">
                  <span>{{ anaDataTitle }}</span>
                  <img src="../assets/image/anaDataTitle.png" />
                  <p class="anaDataClose" @click="anaDataClose">
                    <img src="../assets/image/close.png" />
                  </p>
                </h1>
                <div id="anaData" class="clearfix" v-show="anaDataCnt"></div>
              </div>
              <div class="chartBox clearfix">
                <div id="myChart" :style="{ width: '90%', height: '400px' }" v-show="graphShow"></div>
                <ul v-show="graphShow" class="chartChange" style="padding-bottom:50px">
                  <li @click="legendClick('1')" :class="{ on: changeOnDataType == 1 }">
                    <img src="../assets/image/chartChange1.png" />
                    <span>商品</span>
                  </li>
                  <li @click="legendClick('2')" :class="{ on: changeOnDataType == 2 }">
                    <img src="../assets/image/chartChange1.png" />
                    <span>地区</span>
                  </li>
                  <li @click="legendClick('3')" :class="{ on: changeOnDataType == 3 }">
                    <img src="../assets/image/chartChange1.png" />
                    <span>贸易方式</span>
                  </li>
                  <li @click="legendClick('4')" :class="{ on: changeOnDataType == 4 }">
                    <img src="../assets/image/chartChange1.png" />
                    <span>国别</span>
                  </li>
                </ul>
                <ul v-show="graphShow" class="chartChange">
                  <li @click="iSchartType('bar')" :class="{ on: changeOn == 0 }">
                    <img src="../assets/image/chartChange1.png" />
                    <span>柱状图</span>
                  </li>
                  <li @click="iSchartType('line')" :class="{ on: changeOn == 2 }">
                    <img src="../assets/image/chartChange3.png" />
                    <span>折线图</span>
                  </li>
                </ul>

              </div>
              <!--  指标说明-->
              <div class="predictWinBox indexCodePopBox" v-if="isIndexCodePopShow">
                <div class="predictWin">
                  <div class="predictTitle indexCodePop">
                    指标说明
                    <img src="../assets/image/close.png" @click="isIndexCodePopShow = false" />
                  </div>
                  <ul>
                    <li v-for="(item, index) in macroIndexCodeArr" :key="index">
                      <div>{{ item.name }}</div>
                      <div>{{ item.value }}</div>
                    </li>
                  </ul>
                </div>
              </div>
              <!-- 列表图片字段值对应关系  -->
              <div class="table-l emptyLeft">
                <el-table ref="multipleTable" id="tableDetailData" :data="tableDataff">
                  <el-table-column type="index" fixed label="序号" width="80" />
                  <el-table-column v-if="getIndex.length" fixed prop="codeTs" label="商品编码" min-width="150" />
                  <el-table-column v-if="getIndex.length" fixed prop="hsNameCn" label="商品名称" show-overflow-tooltip min-width="200" />
                  <el-table-column v-if="getTradePartner.length" :fixed="getIndex.length == 0" prop="originCountry" label="国别编码" min-width="150" />
                  <el-table-column v-if="getTradePartner.length" :fixed="getIndex.length == 0" prop="countryNameCn" label="国别名称" min-width="150" />
                  <el-table-column v-if="getTradeMode.length" prop="tradeMode" label="贸易方式编码" min-width="150" />
                  <el-table-column v-if="getTradeMode.length" prop="tradeModeCn" label="贸易方式名称" min-width="150" />
                  <el-table-column v-if="getRegion.length" prop="tradeCoPort" label="地区编码" min-width="150" />
                  <el-table-column v-if="getRegion.length" prop="tradeCoPortCn" label="地区名称" min-width="150" />
                  <el-table-column v-if="getIndex.length" prop="qty1" label="第一数量" min-width="150" />
                  <el-table-column v-if="getIndex.length" prop="unit1" label="第一计量单位" min-width="150" />
                  <el-table-column v-if="getIndex.length" prop="qty2" label="第二数量" min-width="150" />
                  <el-table-column v-if="getIndex.length" prop="unit2" label="第二计量单位" width="150" />
                  <el-table-column prop="timeCode" label="时间" min-width="150" />
                  <el-table-column prop="price" label="金额" min-width="150" />
                  <el-table-column prop="priceType" label="币种" min-width="150" :formatter="iSpriceType" />
                  <el-table-column prop="ieType" label="进出口类型" min-width="150" :formatter="iSieType" />
                </el-table>
              </div>
              <!-- 分页 -->
              <div class="flex-center">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[20, 40, 60, 80]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <com-foot></com-foot>
  </div>
</template>

<script>
import indexBreadcrumb from "../components/breadcrumb";
import indexHead from "../components/head";
import comFoot from "../components/comfoot";
import html2canvas from "html2canvas";
import _ from 'lodash';
// import "echarts-map/js/china.js";
import XLSX from "xlsx";
import FileSaver from "file-saver";
import { mapGetters } from 'vuex'
import { getHideAreaArr, tabTable } from "./components/macro/table.js";

export default {
  data() {
    return {
      tablist: [
        { label: "商品", value: "1", visible: false },
        { label: "地区", value: "2", visible: false },
        { label: "贸易方式", value: "3", visible: false },
        { label: "国别", value: "4", visible: false }
      ],
      shoutabs: false,
      goodsCodesTsData: [],
      tradPartnerCountryData: [],
      tradeCoPortCnData: [],
      tradeModeData: [],
      oldtime: [],
      oldgoods: [],
      oldregion: [],
      oldtrade: [],
      oldpartner: [],
      page: 1,
      limit: 20,
      total: 0,
      statisticType: "1",
      activeName: "first",
      token: localStorage.getItem("TOKEN_KEY"),
      mainPositionWinShow: false,
      isIndexCodePopShow: false,
      statementShow: true,
      analysisWin: false,
      predictWin: false,
      anaDataShow: false,
      anaDataCnt: true,
      legend: [],
      getIndex: [],
      getTime: [],
      getTimes: [],
      getIndexs: [],
      getRegions: [],
      getRegion: [],
      getTradeMode: [],
      getTradeModes: [],
      getTradePartner: [],
      getTradePartners: [],
      mapYears: [],
      changeOn: 0,
      changeOnDataType: 1,
      macroIndexCodeArr: [],
      tableDataff: [],
      filterText: "",
      downImg: "",
      graphShow: true,
      timeFilterSelectArr: [
        {
          value: 5,
          label: "近5年",
        },
        {
          value: 10,
          label: "近10年",
        },
        {
          value: 20,
          label: "近20年",
        },
      ],
      defaultPropsTime: {
        children: "children",
        label: "label",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      defaultPropscloumn: {
        children: "children",
        label: "label",
      },
      defaultPropsTradeMode: {
        children: "children",
        label: "label",
      },
      defaultPropsTradePartner: {
        children: "children",
        label: "label",
      },
      defaultPropsRegion: {
        children: "children",
        label: "codename",
      },
      dataTradePartner: [],
      dataTradeMode: [],
      data: [],
      dataTime: [
        {
          id: 3,
          label: "全选",
          children: [],
        },
      ],
      dataRegion: [
        {
          id: 2,
          codename: "全选",
          children: [
          ],
        },
      ],
      anaDataTitle: "",
      timeFilterSelectVal: "",
      filterTextTime: "",
      filterTextRegion: "",
      filterTextTradeMode: "",
      filterTextTradePartner: "",
      picName: "",
      cur: 0,
      value: "1",
      chartType: 'bar',
      iETypeRadio: 0,
      currencyTypeRadio: 1
    }
  },
  components: {
    indexHead,
    comFoot,
    html2canvas,
    indexBreadcrumb
  },
  watch: {
    getTradeMode(newVal, oldVal) {
      this.pushLabelIfNotEmpty();
    },
    getIndex(newVal) {
      this.pushLabelIfNotEmpty();
    },
    getTradePartner(newVal) {
      this.pushLabelIfNotEmpty();
    },
    getRegion(newVal) {
      this.pushLabelIfNotEmpty();
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterTextTradeMode(val) {
      this.$refs.treeTradeMode.filter(val);
    },
    filterTextTradePartner(val) {
      this.$refs.treeTradePartner.filter(val);
    },
    filterTextRegion(val) {
      this.$refs.treeRegion.filter(val);
    },
    filterTextTime(val) {
      this.$refs.treeTime.filter(val);
    },
    $route(to, from) {
      // 防止外部跳入重复执行
      if (to.name === from.name) this.reload();
    },
  },
  computed: {
    ...mapGetters({ userInfo: 'getUserInfo' }),
    // 是否显示 地区 tab
    isVisibleAreaTab() {
      let arr = getHideAreaArr();
      return arr.indexOf(this.tableName) < 0;
    },
    tableName() {
      if (this.$route.query.tablename.indexOf("season") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [
          {
            value: 4,
            label: "前4季度",
          },
          {
            value: 8,
            label: "前8季度",
          },
          {
            value: 12,
            label: "前12季度",
          },
        ];
      else if (this.$route.query.tablename.indexOf("month") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [

          {
            value: 12,
            label: "前12月",
          },
          {
            value: 24,
            label: "前24月",
          },
          {
            value: 36,
            label: "前36月",
          },
        ];

      return this.$route.query.tablename || "custom_house_month";
    }
  },
  mounted() {
    $(function () {
      $(".el-badge.item sup").hide();
      var url = window.location.href;
      var loc = url.substring(url.lastIndexOf("=") + 1, url.length);
      if (loc == "beltroad_year") {
        $(".mainBody_tab_tilte li").eq(6).hide();
      }
    });
    this.firstInit();
    this.statistic();
  },
  methods: {
    pushLabelIfNotEmpty() {
      if (this.getIndex.length == 0 && this.getRegion.length == 0 && this.getTradeMode.length == 0 && this.getTradePartner.length == 0) {
        this.tablist = [
          { label: "商品", value: "1", visible: false },
          { label: "地区", value: "2", visible: false },
          { label: "贸易方式", value: "3", visible: false },
          { label: "国别", value: "4", visible: false }
        ]
      } else {
        this.tablist.forEach(tab => {
          switch (tab.value) {
            case "1":
              tab.visible = this.getIndex.length > 0 ? false : true;
              break;
            case "2":
              tab.visible = this.getRegion.length > 0 ? false : true;
              break;
            case "3":
              tab.visible = this.getTradeMode.length > 0 ? false : true;
              break;
            case "4":
              tab.visible = this.getTradePartner.length > 0 ? false : true;
              break;
            default:
              tab.visible = false;
          }
        })
      }
      this.shoutabs = _.filter(this.tablist, function (o) { return !o.visible; });
    },
    iSchartType(v) {
      if (v == 'bar') {
        this.statisticType = "13";
        this.statistic();
        this.changeOn = 0;
      } else {
        this.statisticType = "15";
        this.statistic();
        this.changeOn = 2;
      }
      this.chartType = v
      this.legendClick()
    },
    iSpriceType(row) {
      const map = {
        '1': '人民币',
        '2': '美元'
      }
      return map[row.priceType]
    },
    iSieType(row) {
      const map = {
        '1': '进口',
        '0': '出口',
        '10': '进出口'
      }
      return map[row.ieType]
    },
    paTime(e) {
      if (e == undefined) return
      return this.$dayjs(e).format("YYYY-MM-DD")
    },
    handleCurrentChange(val) {
      this.page = val;
      this.gettable();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.gettable();
    },
    firstInit() {
      var that = this;
      let result = tabTable.find((item) => {
        return item.tableName.indexOf(this.tableName) >= 0;
      });
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      // 获取商品名称
      let data1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getIndex",
            method: "get",
            params: params,
          })
          .then(function (response) {
            that.oldgoods = JSON.parse(JSON.stringify(response.data))
            that.data = that.getClData(response.data);
            resolve(response);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      // 获取时间
      let dataTime1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getTime",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.oldtime = JSON.parse(JSON.stringify(res.data))
            resolve(res);
            // 原始数据
            res.data.sort(function (a, b) {
              return b - a;
            });
            that.timeSource = res.data;
            if (res.data) {
              that.setTimeTrees(res, result);
            }
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      // 获取地区
      let dataRegion1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getRegion",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.oldregion = JSON.parse(JSON.stringify(res.data))
            that.setRegionTrees(res, result);
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      // 获取贸易方式
      let dataTradeMode1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/customHouse/getTradeMode",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.oldtrade = JSON.parse(JSON.stringify(res.data))
            var data = that.getClData(res.data);
            that.dataTradeMode = [
              {
                id: 4,
                label: "全选",
                children: data,
              },
            ];
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      // 获取贸易伙伴
      let dataTradePartner1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/customHouse/getTradePartner",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.oldpartner = JSON.parse(JSON.stringify(res.data))
            var data = that.getClData(res.data);
            that.dataTradePartner = [
              {
                id: 3,
                label: "全选",
                children: data,
              },
            ];
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });

      data1.then(() => {
        return dataTime1;
      }).then(() => {
        return dataTradeMode1;
      }).then(() => {
        return dataTradePartner1;
      }).then(() => {
        return dataRegion1;
      }).then(() => {
        let pageType = this.$route.query.pageType;
        if (pageType === "changeParam") {
          // 自带默认查询数据,从收藏列表页面过来
          let { indexCode, regionCode, timeCode, tradeModeCode, tradeModePartner } = JSON.parse(
            localStorage.getItem("macroCodes")
          );
          this.checkChangeHandle(null, null, null, indexCode.split(","));
          this.checkChangeHandleRegion(null, null, null, regionCode.split(","));
          this.checkChangeHandleMode(null, null, null, tradeModeCode.split(","));
          this.checkChangeHandlePartner(null, null, null, tradeModePartner.split(","));
          this.checkChangeHandleTime(null, null, null, timeCode.split(","));
          // todo  从缓存中拿数据
          return this.termSubmit();
        }
        return that.websingletableGetData();
      })
        .finally(() => {
          that.mainPositionWinShow = false;
        });
    },
    nodeClickHandle(data) {
      this.mainPositionWinShow = true;
      var checkedKeys = this.$refs.tree.getCheckedKeys();
      // 定义递归函数，用于遍历并处理嵌套树结构
      function processNode(node) {
        const index = checkedKeys.indexOf(node.code);
        if (index < 0) {
          checkedKeys.push(node.code);
        } else {
          checkedKeys.splice(index, 1);
        }

        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            processNode(child);
          })
        }
      }

      if (!data.children || data.children.length === 0) {
        processNode(data);
        this.$refs.tree.setCheckedKeys(checkedKeys);
      }
    },
    nodeClickHandleMode(dada) {
      this.mainPositionWinShow = true;
    },
    getClData(list, parentId) {
      if (!parentId) {
        parentId = 0;
      }
      let result = [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].parenid == parentId) {
          list[i].label = list[i].fullname + ` (${list[i].code})`;
          list[i].children = this.getClData(list, list[i].id);
          result.push(list[i]);
        }
      }
      return result;
    },
    // 下载Excel
    output() {
      let { exporttype, username, exportRestrictions } = this.userInfo
      if (!exporttype) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }

      if(exportRestrictions) {
      // 查看权限下的导出条数
      this.$axios.request({
        url: "5100/user/exportRestrictions",
        method: "get",
        params: {
          exportNumber: 0,
          userName: username
        },
      }).then((res) => {
        let Rpieces = res.data
        if (Rpieces == 0) {
          this.$message({
            message: '试用账号，导出已达上限！',
            type: 'warning',
            showClose: true,
            duration: 3000,
            center: true
          });
          return
        } else {
          // 拷贝原有数据
          let original = JSON.parse(JSON.stringify(this.tableDataff));
          if (this.tableDataff.length > Rpieces) {
            let extract = this.tableDataff.slice(0, Rpieces);
            this.tableDataff = extract
            this.$nextTick(() => {
              this.QuickPass()
              this.Exportsuccess(Rpieces,username)
            })
          } else {
            this.QuickPass()
            this.Exportsuccess(this.tableDataff.length,username)
          }
          // 还原原有数据
          setTimeout(()=> {
            this.tableDataff = original
          })
        }
      })
      } else {
        this.QuickPass()
      }
    },
    // 快速导出
    QuickPass() {
      this.statisticType = "3";
      this.statistic();
      var excelName = $(".excelName").html();
      var addFooterHtml =
        '<tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"><td></td><td>数据来源：数据圈</td></tr><tr class="tableNone"><td></td><td>联系人：刘老师</td></tr><tr class="tableNone"><td></td><td>电&nbsp;&nbsp;话：18810308405</td></tr><tr class="tableNone"><td></td><td>E-mail：shicong.liu@shujuquan.com</td></tr>';
      $("#tableDetailData")
        .find(".el-table__fixed-body-wrapper")
        .find("tbody")
        .append(addFooterHtml);
      var wb;
      var fix = document.querySelector(".el-table__fixed");
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#tableDetailData").removeChild(fix)
        );
        document.querySelector("#tableDetailData").appendChild(fix);
        $(".tableNone").remove();
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#tableDetailData"));
      }
      //var wb = XLSX.utils.table_to_book(document.querySelector("#mydialogtable")); //mydialogtable为表格的id名
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      let date = new Date();
      date = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `` + excelName + `${date}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 导出成功
    Exportsuccess(value,user) {
      this.$axios.request({
        url: "5100/user/exportRestrictions",
        method: "get",
        params: {
          exportNumber: value,
          userName: user
        },
      }).then(res => {
        return res.data
      })
    },
    // 保存
    downloadImpByChart() {
      let isexport = this.userInfo.exporttype
      if (!isexport) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }
      this.statisticType = "12";
      this.statistic();
      this.picName = $(".excelName").html();
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等

      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      var this1 = this;
      setTimeout(function () {
        html2canvas(this1.$refs.imageWrapper, {
          backgroundColor: null,
          useCORS: true,
        }).then((canvas) => {
          let dataURL = canvas.toDataURL("image/png");
          this1.downImg = dataURL;
          setTimeout(function () {
            var el = document.getElementById("downImg");
            el.click();
          }, 2000);
        });
      }, 500);
    },
    // 打印
    toImgPrint() { // 转图片打印
      let isexport = this.userInfo.exporttype
      if (!isexport) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }
      html2canvas(document.querySelector("#app"), {
        backgroundColor: '#25262E',
        useCORS: true,
        windowHeight: document.body.scrollHeight

      }).then((canvas) => {

        // let url = canvas.toDataURL('image/jpeg', 1.0)
        const url = canvas.toDataURL()
        this.img = url

        printJS({
          printable: url,
          type: 'image',
          documentTitle: '打印图片'
        })

      })
    },
    print() {
      this.statisticType = "11";
      this.statistic();
      const loading = this.$loading({
        lock: true,
        text: "正在打印...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.toImgPrint();
      loading.close();
    },
    // 递归获取 省市区数组
    getTreeMenuData(arr, parentId) {
      let resultArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (parentId == arr[i].parenid) {
          arr[i].children = this.getTreeMenuData(arr, arr[i].id);
          resultArr.push(arr[i]);
        }
      }
      return resultArr;
    },
    // 设置时间树形左侧菜单
    setTimeTrees(res, result) {
      if (!result || result.time === "1") {
        let timeArr = [];
        for (let e of res.data) {
          timeArr.push({
            id: e,
            label: e,
          });
        }
        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      } else if (result.time === "2") {
        let map = new Map();
        let timeArr = [];
        for (let e of res.data) {
          let year = e.substring(0, 4);
          let value = map.get(year) || [];
          value.push({
            id: e,
            label: e,
          });
          map.set(year, value);
        }
        for (let e of map) {
          let key = e[0];
          let value = e[1];
          timeArr.push({
            id: "id_" + key,
            label: key,
            children: value,
          });
        }

        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      }
    },
    statistic() {
      this.$axios
        .request({
          url: "5100/users-anon/statistic",
          method: "post",
          params: {
            access_token: this.token,
          },
          data: {
            username: this.token,
            type: this.statisticType,
            cnt: 1,
            page: this.$route.query.tablename,
            code: this.getIndex.join(","),
          },
        })
        .then((res) => { })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 设置区域树形左侧菜单
    setRegionTrees(res, result) {
      if (!result || result.area === "1") {
        // 只显示省
        this.dataRegion[0].children = res.data;
      } else if (result.area === "0") {
        // 全国
        this.dataRegion[0].children = [];
      } else {
        let arr = this.getTreeMenuData(res.data, 0);
        this.dataRegion[0].children = arr;
      }
    },
    anaDataClose() {
      document.getElementById("anaData").innerHTML = "";
      this.anaDataShow = false;
    },
    websingletableGetData() {
      // 默认 查看条件
      var that = this;
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      params.append("priceType",1)
      return new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/customHouse/getData",
            method: "get",
            params: params,
          })
          .then(function (res) {
            let { cloumnsData, goodsCodesTsData, tradPartnerCountryData, tradeCoPortCnData, tradeModeData } = res.data
            // 商品 
            that.goodsCodesTsData = goodsCodesTsData
            // 地区
            that.tradeCoPortCnData = tradeCoPortCnData
            // 贸易方式
            that.tradeModeData = tradeModeData
            // 国别
            that.tradPartnerCountryData = tradPartnerCountryData
            that.tableDataff = cloumnsData.data
            that.total = cloumnsData.count
            that.termlook();
            that.legendClick();
            resolve(res);
          }).catch(function (error) {
            reject(error);
          });
      });
    },
    handleCheckedGetRegionChange() {
      this.$refs.treeRegion.setCheckedKeys(this.getRegion);
    },
    conditionsClose() {
      this.mainPositionWinShow = false;
      this.termlook();
      setTimeout(() => {
        this.mainPositionWinShow = false;
      });
    },
    nodeClickHandleRegion(data) {
      this.mainPositionWinShow = true;
    },
    nodeClickHandlePartner(data) {
      this.mainPositionWinShow = true;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label ? data.label.indexOf(value) !== -1 : false;
    },
    filterNodeTime(value, dataTime, node) {
      if (!value) return true;
      return dataTime.label ? value.indexOf(dataTime.label) !== -1 : false;
    },
    filterNodeRegion(value, dataRegion) {
      if (!value) return true;
      return dataRegion.codename ? dataRegion.codename.indexOf(value) !== -1 : false;
    },
    filterNodeTradeMode(value, dataTradeMode) {
      if (!value) return true;
      return dataTradeMode.codename
        ? dataTradeMode.codename.indexOf(value) !== -1
        : false;
    },
    filterNodeTradePartner(value, dataTradePartner) {
      if (!value) return true;
      return dataTradePartner.label ? dataTradePartner.label.indexOf(value) !== -1 : false;
    },
    nodeClickHandleTime(data) {
      this.mainPositionWinShow = true;
    },
    filterTextClear() {
      this.filterText = "";
    },
    filterTextTimeClear() {
      this.filterTextTime = "";
    },
    filterTextRegionClear() {
      this.filterTextRegion = "";
    },
    filterTextTradeModeClear() {
      this.filterTextTradeMode = "";
    },
    filterTextTradePartnerClear() {
      this.filterTextTratePartner = "";
    },
    handleCheckedGetTimeChange() {
      this.$refs.treeTime.setCheckedKeys(this.getTime);
    },
    timeFilterSelectFn(val) {
      //TODO 修改 时间选择器数据
      this.timeFilterSelectVal = val.label;
      this.$refs.treeTime.setCheckedKeys(this.timeSource.slice(0, val.value));
    },
    // 获取默塞选项
    viewConditions() {
      let { oldtime, oldgoods, oldregion, oldtrade, oldpartner } = this;
      let getIndex = [];
      let getRegion = [];
      let getTime = [];
      let getTradeMode = [];
      let getTradePartner = [];

      // 商品
      _.map(oldgoods, goodsitem => {
        if (goodsitem.isShow) {
          getIndex.push(goodsitem.code)
        }
      })
      // 贸易
      _.map(oldtrade, tradeitem => {
        if (tradeitem.isShow) {
          getTradeMode.push(tradeitem.code)
        }
      })
      // 国别
      _.map(oldpartner, partneritem => {
        if (partneritem.isShow) {
          getTradePartner.push(partneritem.code)
        }
      })
      // 时间
      _.map(oldtime, timeitem => {
        getTime.push(timeitem)
      })
      // 地区
      _.map(oldregion, regionitem => {
        if (regionitem.isshow) {
          getRegion.push(regionitem.code)
        }
      })

      return {
        getIndex,
        getRegion,
        getTime,
        getTradePartner,
        getTradeMode
      };
    },
    predict() {
      this.predictWin = true;
      this.analysisWin = false;
      this.statisticalWin = false;
      this.cur = 0;
      this.graphShow = true;
      this.statementShow = true;
    },
    conditionsClear() {
      this.getIndex = [];
      this.getIndexs = [];
      this.$refs.tree.setCheckedKeys([]);
      this.getRegion = [];
      this.getRegions = [];
      this.$refs.treeRegion.setCheckedKeys([]);
      this.getTradeMode = [];
      this.getTradeModes = [];
      this.$refs.treeTradeMode.setCheckedKeys([]);
      this.getTradePartner = [];
      this.getTradePartners = [];
      this.$refs.treeTradePartner.setCheckedKeys([]);
    },
    termlook() {
      window.scrollTo(0, 0);
      let getIndexLength = this.getIndex.length; // 商品
      let getRegionLength = this.getRegion.length; // 地区
      let getTradeModeLength = this.getTradeMode.length; // 贸易方式
      let getTradePartnerLength = this.getTradePartner.length; // 贸易伙伴
      let getTimeLength = this.getTime.length; // 时间
      if (getIndexLength == 0 && getRegionLength == 0 && getTimeLength == 0 && getTradeModeLength == 0 && getTradePartnerLength == 0) {
        let { getIndex, getTradeMode, getTradePartner, getRegion, getTime } = this.viewConditions();
        this.checkChangeHandle(null, null, null, getIndex);
        this.checkChangeHandlePartner(null, null, null, getTradePartner);
        this.checkChangeHandleMode(null, null, null, getTradeMode);
        this.checkChangeHandleRegion(null, null, null, getRegion);
        this.checkChangeHandleTime(null, null, null, getTime);
      } else {
        this.mainPositionWinShow = true;
      }
    },
    anaDataTitleBtn() {
      if (this.anaDataCnt == false) {
        this.anaDataCnt = true;
      } else {
        this.anaDataCnt = false;
      }
    },
    checkChangeHandle(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var checkedKeys = defaultCheckedKeys || this.$refs.tree.getCheckedKeys();
      var getIndexs = [];

      for (var i = 0; i < this.data.length; i++) {
        var data1 = this.data[i];
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                if (data3.children && data3.children.length) {
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(checkedKeys.indexOf(data3.code), 1);
                  }
                  for (var l = 0; l < data3.children.length; l++) {
                    var data4 = data3.children[l];
                    if (data4.children && data4.children.length) {
                      if (checkedKeys.indexOf(data4.code) >= 0) {
                        checkedKeys.splice(checkedKeys.indexOf(data4.code), 1, data4.code);
                      }
                    } else if (checkedKeys.indexOf(data4.code) >= 0) {
                      getIndexs.push({
                        label: data4.fullname,
                        key: data4.code,
                      });
                    }
                  }
                } else if (checkedKeys.indexOf(data3.code) >= 0) {
                  getIndexs.push({
                    label: data3.fullname,
                    key: data3.code,
                  });
                }
              }
              // debugger
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getIndexs.push({
                label: data2.fullname,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getIndexs.push({
            label: data1.fullname,
            key: data1.code,
          });
        }
      }

      this.mainPositionWinShow = true;
      this.getIndex = checkedKeys;
      this.getIndexs = getIndexs;
      if (defaultCheckedKeys) {
        this.$refs.tree.setCheckedKeys(this.getIndex);
      }
    },
    checkChangeHandleTradeMode(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.tree.getCheckedKeys();
      var getIndexs = [];
      for (var i = 0; i < this.data.length; i++) {
        var data1 = this.data[i];
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.codes) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.codes), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.codes) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.codes), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                // 有的匹配code
                if (
                  checkedKeys.indexOf(data3.codes) >= 0 ||
                  checkedKeys.indexOf(data3.code) >= 0
                ) {
                  // 如果匹配的是 code 用codes替换一下
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(
                      checkedKeys.indexOf(data3.code),
                      1,
                      data3.codes
                    );
                  }
                  getIndexs.push({
                    // label: data3.name,
                    label: data3.fullname,
                    key: data3.codes,
                  });
                }
              }
              // debugger
            } else if (checkedKeys.indexOf(data2.codes) >= 0) {
              getIndexs.push({
                // label: data2.name,
                label: data2.fullname,
                key: data2.codes,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.codes) >= 0) {
          getIndexs.push({
            // label: data1.name,
            label: data1.fullname,
            key: data1.codes,
          });
        }
      }

      this.mainPositionWinShow = true;
      this.getIndex = checkedKeys;
      this.getIndexs = getIndexs;
      if (defaultCheckedKeys) {
        this.$refs.tree.setCheckedKeys(this.getIndex);
      }
    },
    checkChangeHandleRegion(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.treeRegion.getCheckedKeys();
      var getRegions = [];
      for (var i = 0; i < this.dataRegion.length; i++) {
        var data1 = this.dataRegion[i];
        //data1
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            //data2
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                //data3
                // if (checkedKeys.indexOf(data3.code) >= 0) {
                //   getRegions.push({
                //     label: data3.codename,
                //     key: data3.code,
                //   });
                // }
                if (data3.children && data3.children.length) {
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(checkedKeys.indexOf(data3.code), 1);
                  }
                  for (var o = 0; o < data3.children.length; o++) {
                    var data4 = data3.children[o];
                    //data4
                    if (checkedKeys.indexOf(data4.code) >= 0) {
                      getRegions.push({
                        label: data4.codename,
                        key: data4.code,
                      });
                    }
                  }
                } else if (checkedKeys.indexOf(data3.code) >= 0) {
                  getRegions.push({
                    label: data3.codename,
                    key: data3.code,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getRegions.push({
                label: data2.codename,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getRegions.push({
            label: data1.codename,
            key: data1.code,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getRegion = checkedKeys;
      this.getRegions = getRegions;
      if (defaultCheckedKeys) {
        this.$refs.treeRegion.setCheckedKeys(this.getRegion);
      }
    },
    checkChangeHandleMode(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.treeTradeMode.getCheckedKeys();
      var getTradeMode = [];
      for (var i = 0; i < this.dataTradeMode.length; i++) {
        var data1 = this.dataTradeMode[i];
        //data1
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            //data2
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                if (data3.children && data3.children.length) {
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(checkedKeys.indexOf(data3.code), 1);
                  }
                  for (var o = 0; o < data3.children.length; o++) {
                    var data4 = data3.children[o];
                    //data4
                    if (checkedKeys.indexOf(data4.code) >= 0) {
                      getTradeMode.push({
                        label: data4.name,
                        key: data4.code,
                      });
                    }
                  }
                } else if (checkedKeys.indexOf(data3.code) >= 0) {
                  getTradeMode.push({
                    label: data3.name,
                    key: data3.code,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getTradeMode.push({
                label: data2.name,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getTradeMode.push({
            label: data1.name,
            key: data1.code,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getTradeMode = checkedKeys;
      this.getTradeModes = getTradeMode;
      if (defaultCheckedKeys) {
        this.$refs.treeTradeMode.setCheckedKeys(this.getTradeMode);
      }
    },
    checkChangeHandlePartner(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.treeTradePartner.getCheckedKeys();
      var getTradePartner = [];
      for (var i = 0; i < this.dataTradePartner.length; i++) {
        var data1 = this.dataTradePartner[i];
        //data1
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            //data2
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                if (data3.children && data3.children.length) {
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(checkedKeys.indexOf(data3.code), 1);
                  }
                  for (var o = 0; o < data3.children.length; o++) {
                    var data4 = data3.children[o];
                    //data4
                    if (checkedKeys.indexOf(data4.code) >= 0) {
                      getTradePartner.push({
                        label: data4.name,
                        key: data4.code,
                      });
                    }
                  }
                } else if (checkedKeys.indexOf(data3.code) >= 0) {
                  getTradePartner.push({
                    label: data3.name,
                    key: data3.code,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getTradePartner.push({
                label: data2.name,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getTradePartner.push({
            label: data1.name,
            key: data1.code,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getTradePartner = checkedKeys;
      this.getTradePartners = getTradePartner;
      if (defaultCheckedKeys) {
        this.$refs.treeTradePartner.setCheckedKeys(this.getTradePartner);
      }
    },
    handleCheckedGetIndexChange() {
      this.$refs.tree.setCheckedKeys(this.getIndex);
    },
    handleCheckedGetTradeModeChange() {
      this.$refs.treeTradeMode.setCheckedKeys(this.getTradeMode);
    },
    handleCheckedGetTradePartnerChange() {
      this.$refs.treeTradePartner.setCheckedKeys(this.getTradePartner);
    },
    checkChangeHandleTime(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.treeTime.getCheckedKeys();
      var getTimes = [];
      for (var i = 0; i < this.dataTime.length; i++) {
        var data1 = this.dataTime[i];
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.id) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.id), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.id) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.id), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                if (checkedKeys.indexOf(data3.id) >= 0) {
                  getTimes.push({
                    label: data3.label,
                    key: data3.id,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.id) >= 0) {
              getTimes.push({
                label: data2.label,
                key: data2.id,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.id) >= 0) {
          getTimes.push({
            label: data1.label,
            key: data1.id,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getTime = checkedKeys;
      this.getTimes = getTimes;
      if (defaultCheckedKeys) {
        this.$refs.treeTime.setCheckedKeys(this.getTime);
      }
    },
    // 获取数据
    termSubmit() {
      const loading = this.$loading({
        lock: true,
        text: "正在提取数据...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.mainPositionWinShow = false;
      var that = this;
      that.page = 1;
      var params = new URLSearchParams();
      var checkedKey = this.$refs.tree.getCheckedKeys();
      // var checkedKeycliumn = this.$refs.treeCloumns.getCheckedKeys();
      var checkedKeyRegion = ["000000"];
      if (that.tableName.indexOf("global_") != -1) {
        checkedKeyRegion = ["000"];
      }
      checkedKeyRegion = this.$refs.treeRegion.getCheckedKeys();
      var checkedKeyTime = this.$refs.treeTime.getCheckedKeys();
      var checkedKeyMode = this.$refs.treeTradeMode.getCheckedKeys()
      var checkedKeyPartner = this.$refs.treeTradePartner.getCheckedKeys()
      let fn = (checkedKey) => {
        var codes = [];
        if (!!checkedKey.length) {
          for (var i = 0; i < checkedKey.length; i++) {
            if (/^id/.test(checkedKey[i])) {
              continue;
            }
            codes.push(checkedKey[i]);
          }
        }
        return codes;
      };

      let codes = fn(checkedKey);
      let times = fn(checkedKeyTime);
      let regions = [...new Set(fn(checkedKeyRegion))];
      let tradeModes = fn(checkedKeyMode)
      let tradePartners = fn(checkedKeyPartner)
      if (regions.length !== 0 || codes.length !== 0 || tradeModes.length !== 0 || tradePartners.length !== 0) {
        params.append("regions", regions.join());
        params.append("codes", codes.join());
        params.append("tradeModes", tradeModes.join());
        params.append("tradePartners", tradePartners.join());
      } else {
        params.append("codes", this.getDefualtMenu("getIndex").join());
        params.append("regions", this.getDefualtMenu("getRegion").join());
        params.append("tradeModes", this.getDefualtMenu("getTradeMode").join());
        params.append("tradePartners", this.getDefualtMenu("getTradePartner").join());
      }
      if (times.length !== 0) {
        params.append("times", times.join());
      } else {
        params.append("times", this.getDefualtMenu("getTime").join());
      }
      params.append("priceType", that.currencyTypeRadio);
      params.append("ieType", that.iETypeRadio);
      params.append("page", that.page);
      params.append("limit", that.limit);
      params.append("tableName", that.tableName);
      this.$axios.request({
        url: "5700/customHouse/findData",
        method: "post",
        data: params,
      }).then(function (res) {
        if (!res.data) {
          alert("此条件下无对应数据");
        }
        let more = that.shoutabs[0].value
        let { cloumnsData, goodsCodesTsData, tradPartnerCountryData, tradeCoPortCnData, tradeModeData } = res.data
        // 商品 
        that.goodsCodesTsData = goodsCodesTsData
        // 地区
        that.tradeCoPortCnData = tradeCoPortCnData
        // 贸易方式
        that.tradeModeData = tradeModeData
        // 国别
        that.tradPartnerCountryData = tradPartnerCountryData
        that.tableDataff = cloumnsData.data
        that.total = cloumnsData.count
        that.iSchartType('bar')
        that.legendClick();
      }).catch(function (error) {
        console.log(error);
      }).finally(() => {
        loading.close();
      });
      this.statisticType = "4";
      this.statistic();
    },
    getDefualtMenu(methodName) {
      let fn = (arr, pushKey) => {
        let result = [];
        for (var i = 0; i < arr.length; i++) {
          if (result.length >= 5) break;
          if (arr[i].children && !!arr[i].children.length) {
            result = fn(arr[i].children, pushKey);
          } else {
            if (_.get(arr[i], pushKey, ""))
              result.push(_.get(arr[i], pushKey, ""));
          }
        }
        return result;
      };

      let obj = {
        getIndex: () => {
          return fn(this.data, "code");
        },
        getRegion: () => {
          return fn(this.dataRegion, "code");
        },
        getTime: () => {
          return fn(this.dataTime, "id");
        },
        getTradeMode: () => {
          return fn(this.dataTradeMode, "code")
        },
        getTradePartner: () => {
          return fn(this.dataTradePartner, "code")
        }
      };
      return obj[methodName]();
    },
    formatDataForLineChart(data) {
      const categories = Object.keys(data);
      const legendDatas = [];
      const legendData = [];
      const seriesData = [];

      for (const category in data) {
        for (const region in data[category]) {
          if (!legendDatas.includes(region)) {
            legendDatas.push(region);
          }
        }
      }

      for (const region of legendDatas) {
        const regionData = {
          name: region.split("|")[1],
          data: []
        };
        legendData.push(region.split("|")[1])

        for (const category in data) {
          const value = data[category][region] || 0;
          regionData.data.push(value);
        }
        seriesData.push(regionData);
      }

      return { categories, legendData, seriesData };
    },

    // 切换时处理数据
    legendClick(e) {
      let index = e == undefined ? '1' : e
      this.value = index
      this.changeOnDataType = index
      let { value, goodsCodesTsData, tradPartnerCountryData, tradeCoPortCnData, tradeModeData } = this
      // 商品
      if (value == 1) {
        this.drawchart(goodsCodesTsData)
      }
      // 地区
      if (value == 2) {
        this.drawchart(tradeCoPortCnData)
      }
      // 贸易方式
      if (value == 3) {
        this.drawchart(tradeModeData)
      }
      // 国别
      if (value == 4) {
        this.drawchart(tradPartnerCountryData)
      }
    },
    // 绘制图表
    drawchart(Data) {
      let sData = this.formatDataForLineChart(Data)
      let { chartType } = this
      let colorarr = ['#4992FF', '#7CFEB2', '#FBDD61', '#F66E76']
      var myChart = this.$echarts.init(document.getElementById("myChart"));
      var chartOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#fff',
            },
          },
        },
        color: colorarr,
        legend: {
          data: sData.legendData,
          textStyle: {
            color: '#fff',
          }
        },
        xAxis: [{
          type: 'category',
          data: sData.categories,
          axisPointer: {
            type: 'shadow',
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        series: sData.seriesData.map(item => ({
          name: item.name,
          type: chartType,
          data: item.data
        }))
      };
      myChart.setOption(chartOption, true);
    },
    // 获取列表
    gettable() {
      var that = this;
      var params = new URLSearchParams();
      var checkedKey = this.$refs.tree.getCheckedKeys();
      // var checkedKeycliumn = this.$refs.treeCloumns.getCheckedKeys();
      var checkedKeyRegion = ["000000"];
      if (that.tableName.indexOf("global_") != -1) {
        checkedKeyRegion = ["000"];
      }
      checkedKeyRegion = this.$refs.treeRegion.getCheckedKeys();
      var checkedKeyTime = this.$refs.treeTime.getCheckedKeys();
      var checkedKeyMode = this.$refs.treeTradeMode.getCheckedKeys()
      var checkedKeyPartner = this.$refs.treeTradePartner.getCheckedKeys()
      let fn = (checkedKey) => {
        var codes = [];
        if (!!checkedKey.length) {
          for (var i = 0; i < checkedKey.length; i++) {
            if (/^id/.test(checkedKey[i])) {
              continue;
            }
            codes.push(checkedKey[i]);
          }
        }
        return codes;
      };

      let codes = fn(checkedKey);
      let times = fn(checkedKeyTime);
      let regions = [...new Set(fn(checkedKeyRegion))];
      let tradeModes = fn(checkedKeyMode)
      let tradePartners = fn(checkedKeyPartner)
      if (regions.length !== 0 || codes.length !== 0 || tradeModes.length !== 0 || tradePartners.length !== 0) {
        params.append("regions", regions.join());
        params.append("codes", codes.join());
        params.append("tradeModes", tradeModes.join());
        params.append("tradePartners", tradePartners.join());
      } else {
        params.append("codes", this.getDefualtMenu("getIndex").join());
        params.append("regions", this.getDefualtMenu("getRegion").join());
        params.append("tradeModes", this.getDefualtMenu("getTradeMode").join());
        params.append("tradePartners", this.getDefualtMenu("getTradePartner").join());
      }
      if (times.length !== 0) {
        params.append("times", times.join());
      } else {
        params.append("times", this.getDefualtMenu("getTime").join());
      }
      params.append("priceType", that.currencyTypeRadio);
      params.append("ieType", that.iETypeRadio);
      params.append("page", that.page);
      params.append("limit", that.limit);
      params.append("tableName", that.tableName);
      this.$axios.request({
        url: "5700" + "/customHouse/findData",
        method: "post",
        data: params,
      }).then(function (res) {
        that.tableDataff = res.data.cloumnsData.data
        that.total = res.data.cloumnsData.count
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tree {
  overflow-y: auto;
  overflow-x: auto;
  /* width: 80px; */
  height: 800px;
}

/deep/ .table-l {
  position: relative;
}

/deep/ .el-table__body-wrapper {
  border-top: 0 !important;
}

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #1f2027;
  z-index: 4;
}

.timeSelect {
  width: 64%;
  color: rgb(255, 255, 255);
  background: #25262e;
  height: 30px;
  line-height: 30px;
  padding-left: 10%;
}

.inputBlack input {
  background: #fff;
  color: #000;
}

.indexCodePopBox {
  .predictWin {
    top: 25%;
  }

  .indexCodePop {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  ul {
    background: #25262e;
    box-shadow: #000;

    li {
      display: flex;

      div {
        flex: 1;
        padding: 10px;
      }

      div:first-child {
        border-right: 1px solid #4b4c53;
      }
    }

    li:not(:last-child) {
      border-bottom: 1px solid #4b4c53;
    }
  }
}

.mainMap {
  position: relative;

  .mapYears {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);

    .mapIcon1 {
      position: absolute;
      right: 2px;
      top: -17px;
      width: 18px;
      padding: 0 10px;
    }

    .mapIcon2 {
      position: absolute;
      right: 2px;
      bottom: -17px;
      width: 18px;
      padding: 0 10px;
    }

    ul {
      li {
        position: relative;
        height: 60px;
        display: flex;
        align-items: center;
        padding-right: 30px;

        .mapIcon {
          width: 20px;
          height: 20px;
          margin-left: 10px;
          z-index: 99;
          position: absolute;
          right: 0;
          background: #25262e;
          padding: 5px 0;
        }

        .mapIconActive {
          width: 26px;
          height: 26px;
          right: -3px;
        }

        .mapYears-line {
          position: absolute;
          right: 10px;
          width: 1px;
          height: 100%;
          background: #fff;
          top: 0px;
          z-index: 88;
        }
      }
    }
  }
}

/deep/ .el-tabs--card > .el-tabs__header .el-tabs__item {
  text-align: center;
}

/deep/ .el-table thead.is-group th.el-table__cell {
  background: #25262e;
}
/deep/
  .el-tabs--top.el-tabs--card
  > .el-tabs__header
  .el-tabs__item:nth-child(2) {
  padding-left: 5px;
}
/deep/ .el-tabs__item {
  /*width: 33.3%;*/
  padding: 0px 5px;
}
/deep/ #tab-1.el-tabs__item {
  width: 100px;
}
/deep/ #tab-2.el-tabs__item {
  width: 100px;
}
/deep/ #tab-3.el-tabs__item {
  width: 100px;
}
/deep/ #tab-4.el-tabs__item {
  width: 100px;
  padding-right: 0px;
}
/deep/ .el-radio__label {
  color: #fff;
  font-size: 16px;
}

.el-radio-color {
  color: #fff;
}
.el-radio-padding {
  padding: 7px 0;
}
.el-radio-padding-left {
  color: #fff;
  padding-left: 50px;
}

/deep/ .el-radio {
  margin-right: 20px;
}
</style>